Problem storing text to a String[] and then storing the array to a Vector.

Posted by hatboysam on Stack Overflow See other posts from Stack Overflow or by hatboysam
Published on 2010-04-24T16:03:45Z Indexed on 2010/04/27 5:03 UTC
Read the original article Hit count: 391

Filed under:
|

OK so for background I've only been using Java for a little more than a week and I am making a basic GUI "Recipe Book" application just to test out some of the techniques I've learned. Currently I'm working on the "Add New Recipe" page that allows the user to make a new recipe by adding ingredients one at a time. The ingredients have 3 attributes: Name, amount, and unit (like cups, oz, etc) that come from two text fields and a combo box respectively. The 3 values are stores as strings to a String array that represents the ingredient, then the arrays are stored in a vector that holds all of the ingredients for one recipe. When an ingredient is added, the user first types in the 3 necessary values into empty boxes/combo box dropdown and then clicks "Add Ingredient". Here is my code for when the button is clicked:

public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == addIngredientButton) {
        //make sure 3 ingredient fields are not blank
        if (!ingredientNameField.getText().equals("") && !ingredientAmountField.getText().equals("") && !ingredientUnitDropdown.getSelectedItem().equals("")) {
            tempIngredientsArray[0] = ingredientNameField.getText(); //set ingredient name to first position in array
            tempIngredientsArray[1] = ingredientAmountField.getText(); //set ingredient amount to second position in array
            tempIngredientsArray[2] = (String) ingredientUnitDropdown.getSelectedItem(); //set ingredient unit to third position in array
            int ingredientsVectorSize = tempRecipe.ingredientsVector.size();
            tempRecipe.ingredientsVector.add(this.tempIngredientsArray);  //why would it matter if this and previous statement were switched
            for (int k = 0; k < ingredientsVectorSize + 1; k++ ) {
                liveIngredientsListArea.append("\n" + tempRecipe.makeIngredientSentence(k));
                System.out.println(Arrays.toString(tempIngredientsArray));  //shows that tempIngredientsArray gets messed up each time
                }
            }

Now here's the really strange problem I've been having. The first time the user adds an ingredient everything works fine. The second time, the String[] for that ingredient seems to be duplicated, and the third time it's triplicated. Aka the first time it runs the System.out.println might return "{Sugar, 3, Cups}" and the second time it will return "{Flour, 2, Oz.} {Flour, 2, Oz.}" etc. What's causing this strange problem? All help greatly appreciated, let me know if you need any clarification.

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays